package api

import "C"
import (
	"errors"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"github.com/smash-llj/Nexa-server/global"
	"github.com/smash-llj/Nexa-server/models"
	"github.com/smash-llj/Nexa-server/models/request"
	"github.com/smash-llj/Nexa-server/utils"
)

type AiApi struct {
	BaseApi
}

func NewAiApi() AiApi {
	return AiApi{
		BaseApi: NewBaseApi(),
	}
}

// GetAiSessionGroup  获取最近会话List
func (a *AiApi) GetAiSessionGroup(C *gin.Context) {
	a.BaseApi.C = C
	var res []models.AIMessageSession
	userId := utils.GetUserId(C)
	result := global.DB.Model(&models.AIMessageSession{}).Preload("Messages").Where("user_id=? And status=?", userId, 1).Order("created_at desc").Find(&res)
	if result.Error != nil {
		a.Fail(Response{Msg: result.Error})
		return
	}
	a.Success(Response{Data: res})
}

// CreateAiSessionGroup 创建会话
func (a *AiApi) CreateAiSessionGroup(C *gin.Context) {
	a.BaseApi.C = C
	userId := utils.GetUserId(C)
	aiMessageGroup := models.AIMessageSession{
		UserId:    userId,
		Title:     "新的会话",
		SessionId: uuid.New().String(),
	}
	result := global.DB.Create(&aiMessageGroup)
	if result.Error != nil {
		a.Fail(Response{Msg: errors.New("创建失败")})
		return
	}
	a.Success(Response{Data: aiMessageGroup})
}

// DeleteAiSession 删除会话
func (a *AiApi) DeleteAiSession(c *gin.Context) {
	a.BaseApi.C = c
	sessionId := c.Param("sessionId")
	if sessionId == "" {
		a.Fail(Response{
			Msg: "sessionId不能为空",
		})
		return
	}
	result := global.DB.Model(&models.AIMessageSession{}).Where("session_id=?", sessionId).Update("status", 0)
	if result.Error != nil {
		a.Fail(Response{Msg: result.Error})
		return
	}
	a.Success(Response{Msg: "删除成功"})
}

// GetAIMessageList 获取Ai历史会话消息
func (a *AiApi) GetAIMessageList(C *gin.Context) {
	var Req request.GetAIMessageListReq
	if err := a.BindData(BuildBaseApiOptions{C: C, Dto: &Req}); err != nil {
		a.Fail(Response{Msg: err.Error()})
		return
	}
	list, err := utils.FindMessageHistoryList(Req.SessionId)
	if err != nil {
		a.Fail(Response{Msg: err.Error()})
		return
	}
	a.Success(Response{Data: list})
}

// AskAI 发送消息给AI
func (a *AiApi) AskAI(c *gin.Context) {
	c.Writer.Header().Set("Content-Type", "text/event-stream")
	c.Writer.Header().Set("Cache-Control", "no-cache")
	c.Writer.Header().Set("Connection", "keep-alive")
	var req request.AskAiMessageReq
	if err := a.BindData(BuildBaseApiOptions{C: c, Dto: &req}); err != nil {
		a.Fail(Response{Msg: err.Error()})
		return
	}
	// 保存用户消息
	if err := utils.SaveRecordMessage(req.Content, req.SessionId, global.AIMessageUser); err != nil {
		a.Fail(Response{Msg: "保存数据失败"})
		return
	}

	// 获取历史消息记录
	HistoryList, err := utils.FindMessageHistoryList(req.SessionId)
	if HistoryList == nil || err != nil {
		a.Fail(Response{Msg: "查询历史数据失败"})
		return
	}

	//构建 对话历史
	MessageList := utils.BuildChatList(HistoryList)

	// 处理 AI 回应并保存
	if !utils.AskChat(c, MessageList, req.SessionId) {
		a.Fail(Response{Msg: "Ai 响应处理错误"})
		return
	}
}
